package cn.jfstu.freenote.dao.conf;

import cn.jfstu.freenote.pojo.DatabaseConfig;
import cn.jfstu.freenote.pojo.RuntimeEnvironment;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * 数据源配置
 * @author 贾俊峰
 * @version 1.0
 * @date 2016/11/29 14:02
 */
@Configuration
public class DataSourceConfig {

    @Resource
    private RuntimeEnvironment runtimeEnvironment;

    @Bean
    public DataSource dataSource() throws SQLException {
        DatabaseConfig databaseConfig = new DatabaseConfig(runtimeEnvironment);
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(databaseConfig.getDriverName());
        dataSource.setUrl(databaseConfig.getUrl());
        dataSource.setUsername(databaseConfig.getUsername());
        dataSource.setPassword(databaseConfig.getPassword());
        dataSource.setInitialSize(1);
        dataSource.setMaxActive(50);
        dataSource.setMinIdle(1);
        dataSource.setMaxWait(60000);
        dataSource.setValidationQueryTimeout(1);
        dataSource.setMinEvictableIdleTimeMillis(300000);
        dataSource.setTestOnBorrow(false);
        dataSource.setTestOnReturn(false);
        dataSource.setTestWhileIdle(true);
        dataSource.setTimeBetweenEvictionRunsMillis(60000);
        dataSource.setValidationQuery("SELECT 1");
        dataSource.setFilters("config");
        dataSource.setConnectionProperties("config.decrypt=true;config.decrypt.key=" + databaseConfig.getPublicKey());
        return dataSource;
    }
}
